#include "StdAfx.h"
#include "ylLogDataGridView.h"
#include "ylLogMessageGroup.h"
#include "ylSessionData.h"
#include "ylLogMessageTemplate.h"
#include "ylLogMessageClass.h"

using namespace yoctolog_viewer;


LogDataGridView::LogDataGridView( void )
{
	InitializeComponent();

	this->VirtualMode = true;

	// Connect the virtual-mode events to event handlers. 
	this->CellValueNeeded += gcnew
		DataGridViewCellValueEventHandler( this, &LogDataGridView::OnCellValueNeeded );
	this->CellFormatting += gcnew
		DataGridViewCellFormattingEventHandler( this, &LogDataGridView::OnCellFormatting );
}


void LogDataGridView::OnCellFormatting( Object^ /*sender*/, System::Windows::Forms::DataGridViewCellFormattingEventArgs^ e )
{
	if( m_pCurrentGroup == nullptr )
		return;

	if( e->RowIndex >= m_pCurrentGroup->m_vecMessageList->Count )
		return;

	unsigned int uiMessageIndex = m_pCurrentGroup->m_vecMessageList[e->RowIndex];
	LogMessage ^pMessage = m_pSessionData->GetMessage(uiMessageIndex);

	LogMessageTemplate ^pTemplate = pMessage->m_pTemplate;

	if( pTemplate->m_pMessageClass->m_textColor )
		e->CellStyle->ForeColor = *pTemplate->m_pMessageClass->m_textColor;
	if( pTemplate->m_pMessageClass->m_bgColor )
		e->CellStyle->BackColor = *pTemplate->m_pMessageClass->m_bgColor;

	FontStyle xFontStyle = FontStyle::Regular;
	if( pTemplate->m_pMessageClass->m_bBold == true )
		xFontStyle = FontStyle::Bold;
	e->CellStyle->Font = gcnew System::Drawing::Font( "Microsoft Sans Serif", 8.25f, xFontStyle );
	e->FormattingApplied = true;
}


void LogDataGridView::OnCellValueNeeded( Object^ /*sender*/, System::Windows::Forms::DataGridViewCellValueEventArgs^ e )
{
	if( m_pCurrentGroup == nullptr )
		return;

	if( e->RowIndex >= m_pCurrentGroup->m_vecMessageList->Count )
		return;

	unsigned int uiMessageIndex = m_pCurrentGroup->m_vecMessageList[e->RowIndex];
	LogMessage ^pMessage = m_pSessionData->GetMessage(uiMessageIndex);

	if( !pMessage )
		return;

	LogMessageTemplate ^pTemplate = pMessage->m_pTemplate;

	if( e->ColumnIndex == 0 )
	{
		e->Value = pTemplate->m_pMessageClass->m_pName;
	}

	if( e->ColumnIndex == 1 )
	{
		String ^strFormattedString = gcnew String("");
		int iParameterIndex = 0;

		for( int i = 0; i < pTemplate->m_strText->Length; i++ )
		{
			if( pTemplate->m_strText[i] == '%' )
			{
				strFormattedString += pMessage->m_vecParameters[iParameterIndex];
				++iParameterIndex;

				++i;
			}
			else
			{
				strFormattedString += pTemplate->m_strText[i];
			}
		}

		e->Value = strFormattedString;
	}
}


void LogDataGridView::SetGroup(LogMessageGroup ^pGroup)
{
	m_pCurrentGroup = pGroup;
}


void LogDataGridView::SetSessionData(SessionData ^pSessionData)
{
	m_pSessionData = pSessionData;
}